<?php

namespace app\admin\controller;
use app\admin\controller\Main;
use think\Controller;
use think\Db;
use think\Exception;
use app\commons\model\Member;

class Merch extends Main {

    public function index() {

        $_GPC = input();
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 1);
        $row = Member::where('ismerch', 1);
        if (isset($_GPC['agent_id']) && intval($_GPC['agent_id']) != 0) {
            $row = $row->where(['agent_id' => $_GPC['agent_id']]);
        }
        if (!empty($_GPC['id'])) {
            $row = $row->where('id', $_GPC['id']);
        }
        if (!empty($_GPC['nickname'])) {
            $row = $row->whereLike('nickname', "%{$_GPC['nickname']}%");
        }
        if (!empty($_GPC['openid'])) {
            $row = $row->whereLike('openid', "%{$_GPC['openid']}%");
        }
        if (isset($_GPC['gender']) && $_GPC['gender'] != '') {
            $row = $row->where('gender', $_GPC['gender']);
        }
        if (!empty($_GPC['mobile'])) {
            $row = $row->whereLike('mobile', "%{$_GPC['mobile']}%");
        }
//        $data = $row->paginate($page);
        $count = $row->count();
        $data = $row->page($page, $limit)->order('createtime', 'DESC')->select();
        return jsonpp($data,$count);
    }

    public function add() {
        if ($this->request->isPost()) {
            $_GPC['data'] = $this->data['data'];
            try {
                $token = check_formtoken();
                unset($_GPC['data']['token']);
                $isupdate = false;
                $_GPC['data']['ismerch'] = 1;
                $_GPC['data']['createtime'] = time();
                $_GPC['data']['endtime'] = strtotime($_GPC['data']['endtime']);
                list($msec, $sec) = explode(' ', microtime());
                $msectime = (float) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
                $_GPC['data']['salt'] = $msectime;
                if ($_GPC['data']['pwd'] == '') {
                    $_GPC['data']['pwd'] = md5('123456' . $msectime);
                } else {
                    $_GPC['data']['pwd'] = md5($_GPC['data']['pwd'] . $msectime);
                }
                $result = Member::where(array('openid' => $_GPC['data']['openid']))->find();
                if (!empty($result) || $result === 0) {
                    if ($result['ismerch'] == '1') {
                        return jsonp_error(422,'商户已存在！');
                    }
                    if ($_GPC['data']['avatar'] == '/upload/avatar.png') {
                        unset($_GPC['data']['avatar']);
                    }
                    if ($_GPC['data']['nickname'] == '') {
                        unset($_GPC['data']['nickname']);
                    }
                    if (intval($_GPC['data']['agent_id']) > 0) {
                        $agent = Db::name('member')->where(array('id' => $_GPC['data']['agent_id']))->find();
                        if ($agent['num'] != 0 && $_GPC['data']['num'] == 0) {
                            return jsonp_error(422,'点数必须大于0！');
                        }
                        if ($agent['num'] != 0) {
                            $isupdate = true;
                            if ($agent['num'] == -1) {
                                $agent['num'] = 0;
                            }
                            $agent['num'] += $result['num'];
                            if ($agent['num'] < $_GPC['data']['num']) {
                                return jsonp_error(422,'代理点数剩余：' . $agent['num'] . '，点数最多只能填写：' . $agent['num'] . '！');
                            }
                        }
                    }
                    $result = Member::where(array('id' => $result['id']))->update($_GPC['data']);
                } else {
                    try {
                        if (intval($_GPC['data']['agent_id']) > 0) {
                            $agent = Db::name('member')->where(array('id' => $_GPC['data']['agent_id']))->find();
                            if ($agent['num'] != 0 && $_GPC['data']['num'] == 0) {
                                return jsonp_error(422,'点数必须大于0！');
                            }
                            if ($agent['num'] != 0) {
                                $isupdate = true;
                                if ($agent['num'] == -1) {
                                    $agent['num'] = 0;
                                }
                                if ($agent['num'] < $_GPC['data']['num']) {
                                    return jsonp_error(422,'代理点数剩余：' . $agent['num'] . '，点数最多只能填写：' . $agent['num'] . '！');
                                }
                            }
                        }
                        $result = Db::name('member')->insert($_GPC['data']);
                    }catch (Exception $exception){
                        return jsonp_error(422,$exception->getMessage());
                    }

                }
                if (!empty($result) || $result === 0) {
                    if (intval($_GPC['data']['agent_id']) > 0 && $_GPC['data']['agent_id'] != $id && $isupdate) {
                        $agent['num'] -= $_GPC['data']['num'];
                        if ($agent['num'] == 0 && $_GPC['data']['num'] != 0) {
                            $agent['num'] = -1;
                        }
                        Db::name('member')->where(array('id' => $agent['id']))->update(array('num' => $agent['num']));
                    }
                    return jsont(array('token' => $token),0,'添加成功');
                } else {
                    return jsont(array('token' => $token),1,'添加失败！');
                }
            }catch (Exception $exception){
                json_old([],1,$exception->getMessage());
            }

        }

        $data = array('avatar' => '/upload/avatar.png');
        return jsonp(get_upload_data($data));
    }

    public function edit() {
        $_GPC = $this->data;
        $id = $_GPC['id'];
        $data = Db::name('member')->where(array('id' => $id))->find();
        if ($this->request->isPost()) {
            $token = check_formtoken();
            unset($_GPC['data']['token']);
            $isupdate = false;
            if (intval($_GPC['data']['agent_id']) > 0 && $_GPC['data']['agent_id'] != $id) {
                $agent = Db::name('member')->where(array('id' => $_GPC['data']['agent_id']))->find();
                if ($agent['num'] != 0 && $_GPC['data']['num'] == 0) {
                    return jsonp_error(422,点数必须大于0！);
                }
                if ($agent['num'] != 0) {
                    $isupdate = true;
                    if ($agent['num'] == -1) {
                        $agent['num'] = 0;
                    }
                    $agent['num'] += $data['num'];
                    if ($agent['num'] < $_GPC['data']['num']) {
                        return jsonp_error(422, '代理点数剩余：' . $agent['num'] . '，点数最多只能填写：' . $agent['num'] . '！');
                    }
                }
            }
            $_GPC['data']['ismerch'] = 1;
            $_GPC['data']['endtime'] = strtotime($_GPC['data']['endtime']);
            if ($_GPC['data']['pwd'] == '') {
                unset($_GPC['data']['pwd']);
            } else {
                list($msec, $sec) = explode(' ', microtime());
                $msectime = (float) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
                $_GPC['data']['pwd'] = md5($_GPC['data']['pwd'] . $msectime);
                $_GPC['data']['salt'] = $msectime;
            }
            $result = Db::name('member')->where(array('id' => $id))->update($_GPC['data']);
            if (!empty($result) || $result === 0) {
                if (intval($_GPC['data']['agent_id']) > 0 && $_GPC['data']['agent_id'] != $id && $isupdate) {
                    $agent['num'] -= $_GPC['data']['num'];
                    if ($agent['num'] == 0 && $_GPC['data']['num'] != 0) {
                        $agent['num'] = -1;
                    }
                    Db::name('member')->where(array('id' => $agent['id']))->update(array('num' => $agent['num']));
                }
                return jsont(array('token' => $token),0,'修改成功！');
            } else {
                return jsont([],1,'提交失败！');
            }
        }
        $data['endtime'] = date('Y-m-d', $data['endtime']);
        return jsonp($data);
    }

    public function del() {
        $_GPC = input();
        $id = $_GPC['id'];
        if ($this->request->isPost()) {
            $result = Member::destroy(function($query) use ($id){
                $query->where('id','in',$id);
            });
            if($result){
                jsont([],0,'删除成功！');
            }
            jsont([], 1, '删除失败');
        }
        json([], 1, 'error');
    }

    public function createsale() {
        $_GPC = input();
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 1);
        $row = Db::name('createsale');
        if (!empty($_GPC['realname'])) {
            $row = $row->whereLike('realname', "%{$_GPC['realname']}%");
        }
        if (!empty($_GPC['mobile'])) {
            $row = $row->whereLike('mobile', "%{$_GPC['mobile']}%");
        }
        if (isset($_GPC['status']) && $_GPC['status'] != '') {
            $row = $row->where('status', $_GPC['status']);
        }
        $data = $row->page($page, $limit)->order('createtime', 'DESC')->select();
        $count = $row->count();
        jsonp($data, $count);
    }

    public function createsalestatus() {
        $_GPC = input();
        $id = $_GPC['id'];
        $status = $_GPC['status'];
        if ($this->request->isPost()) {
            $result = Db::name('createsale')
            ->where(array('id' => $id))
            ->update(array('status' => $status));
            if (!empty($result) || $result === 0) {
                json('success', 0, '修改成功！');
            } else {
                json('error', 1, '修改失败！');
            }
        }
        json('', 1, 'error');
    }

}
